package com.zhijian.warehouse.manage.util;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author HCG
 * @version 1.0
 * @date 2022/5/12
 */
public class NumUtil {

    public static BigDecimal add(BigDecimal... bigDecimals) {
        if (Objects.isNull(bigDecimals) || bigDecimals.length == 0) {
            return BigDecimal.ZERO;
        }
        BigDecimal result = BigDecimal.ZERO;
        for (BigDecimal bigDecimal : bigDecimals) {
            result = result.add(Objects.nonNull(bigDecimal) ? bigDecimal : BigDecimal.ZERO);
        }
        return result;
    }

    public static BigDecimal sqrt(BigDecimal n, int s) {
        BigDecimal two = BigDecimal.valueOf(2);

        // Obtain the first approximation
        BigDecimal x = n
                .divide(BigDecimal.valueOf(3), s, BigDecimal.ROUND_DOWN);
        BigDecimal lastX = BigDecimal.valueOf(0);

        // Proceed through 50 iterations
        for (int i = 0; i < 50; i++) {
            x = n.add(x.multiply(x)).divide(x.multiply(two), s,
                    BigDecimal.ROUND_DOWN);
            if (x.compareTo(lastX) == 0) {
                break;
            }
            lastX = x;
        }
        return x;
    }

    public static Integer[] range(int start, int stop, int step) {
        if (start < stop) {
            step = Math.abs(step);
        } else {
            if (start <= stop) {
                return new Integer[]{start};
            }

            step = -Math.abs(step);
        }

        int size = Math.abs((stop - start) / step) + 1;
        Integer[] values = new Integer[size];
        int index = 0;
        int i = start;

        while (true) {
            if (step > 0) {
                if (i > stop) {
                    break;
                }
            } else if (i < stop) {
                break;
            }

            values[index] = i;
            ++index;
            i += step;
        }

        return values;
    }
}
